package com.moyv.schoolbbs.ui.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;

import com.bumptech.glide.Glide;
import com.moyv.schoolbbs.R;
import com.moyv.schoolbbs.base.chat.data.DialogData;
import com.moyv.schoolbbs.base.chat.data.SealData;
import com.moyv.schoolbbs.base.chat.server.MessagesServer;
import com.moyv.schoolbbs.bean.model.Dialog;
import com.moyv.schoolbbs.bean.model.Message;
import com.moyv.schoolbbs.util.ToastUtils;
import com.stfalcon.chatkit.messages.MessageInput;
import com.stfalcon.chatkit.messages.MessagesList;
import com.stfalcon.chatkit.messages.MessagesListAdapter;

import java.util.ArrayList;
import java.util.Date;

import static com.moyv.schoolbbs.config.AccountConstant.ACCOUNT;

public class ChatActivity extends AppCompatActivity
        implements MessagesListAdapter.SelectionListener,
        MessagesListAdapter.OnLoadMoreListener, MessageInput.InputListener,
        MessageInput.AttachmentsListener {

    private int addCount = 5;
    private final int TOTAL_MESSAGES_COUNT = 20;
    private static MessagesServer.Conversation conversation;
    private static MessagesServer messagesServer;
    private static Dialog dialog;

    private static DialogData dialogData;
    private MessagesList messagesList;
    private MessagesListAdapter<Message> messagesListAdapter;
    private MessageInput input;

    private Menu menu;
    private int selectionCount;
    private Date lastLoadedDate;

    public static void open(Context context, MessagesServer ms, Dialog d, DialogData dd) {
        messagesServer = ms;
        dialog = d;
        dialogData = dd;
        context.startActivity(new Intent(context, ChatActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        messagesList = findViewById(R.id.messagesList);
        initAdapter();
        input = findViewById(R.id.input);
        input.setAttachmentsListener(this);
        input.setInputListener(this);

        System.out.println(dialog);
        onChat();
    }

    private void onChat() {
        if (messagesServer != null) {
            conversation = messagesServer.createConversation(SealData.getId(dialog.getId()), (name, mes) -> {
                System.out.println("ChatActity消息回调");
                this.runOnUiThread(() -> {
                    messagesListAdapter.addToStart(SealData.getMessage(name, mes, new Date()), true);
                });
            });
        }
    }

    private void initAdapter() {
        System.out.println("ACOUNT->" + ACCOUNT);
        messagesListAdapter = new MessagesListAdapter<>(String.valueOf(ACCOUNT), (imageView, url, payload) -> Glide.with(this).load(url).into(imageView));
        messagesListAdapter.enableSelectionMode(this);
        messagesListAdapter.setLoadMoreListener(this);
//        messagesListAdapter.setDateHeadersFormatter(this);
        messagesList.setAdapter(messagesListAdapter);
        onLoadMore(0, 1);
    }

    @Override
    public void onSelectionChanged(int count) {

    }

    @Override
    public void onLoadMore(int page, int totalItemsCount) {
        System.out.println("正在加载消息记录---page->" + page + "---totalItemsCount->" + totalItemsCount);
        loadMessages(page);
    }

    private void loadMessages(int page) {
        //imitation of internet connection
        new Handler().postDelayed(() -> {
//            ArrayList<Message> messages = MessagesFixtures.getMessages(lastLoadedDate);
//            lastLoadedDate = messages.get(messages.size() - 1).getCreatedAt();
//            messagesListAdapter.addToEnd(messages, false);
            ArrayList<Message> localMessages = dialogData.getLocalMessages(dialog.getId(), page, TOTAL_MESSAGES_COUNT);
            messagesListAdapter.addToEnd(localMessages, false);
        }, 100);

    }

    @Override
    public void onAddAttachments() {
//        messagesListAdapter.addToStart(
//                MessagesFixtures.getImageMessage(), true);
//        if (addCount > 0) {
//            ToastUtils.show("再点击 " + (addCount--) + " 次解锁隐藏功能！");
//        } else {
//            ToastUtils.show("又骗到一个hhh");
//        }
    }

    @Override
    public boolean onSubmit(CharSequence input) {
        String mes = input.toString();
        Message message = SealData.getMessage(String.valueOf(ACCOUNT), mes, new Date());
        messagesListAdapter.addToStart(message, true);
        conversation.sendMessage(mes);
        dialogData.saveMessage(dialog.getId(), message.getId(), mes, message.getCreatedAt(), true);
        return true;
    }
}